package com.qunar.flight.myserver;

import java.nio.channels.SelectionKey;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

import org.apache.log4j.Logger;

public class AcceptHandler implements Handler {
	static Logger logger = Logger.getLogger(AcceptHandler.class);
	private ServerSocketChannel channel;
	private Dispatcher dsp;
	private SelectionKey sk;

	AcceptHandler(ServerSocketChannel ssc, Dispatcher dsp) {
		this.channel = ssc;
		this.dsp = dsp;
	}

	public void setSk(SelectionKey sk){
		this.sk=sk;
	}
	public void handle(SelectionKey sk){
		try{
		SocketChannel sc=channel.accept();
		if(null==sc){
			return;
		}
		logger.info("处理中..."+sk.interestOps()+":"+sk);
		sc.configureBlocking(false);
		Handler rh=new RequestHandler(sc);
		dsp.register(sc, SelectionKey.OP_READ, rh);
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public void run(){
		try {
			handle(sk);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
